package 链表;

public class 删除链表的倒数第n个结点 {
    public  class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
    public  ListNode removeNthFromEnd(ListNode head, int n) {
        //使用快慢指针来求解
        ListNode pre=new ListNode(0);
        pre.next=head;
        ListNode start=pre,end=pre;
        while (n!=0){
            start=start.next;
            n--;
        }
        while (start.next!=null){
            start=start.next;
            end=end.next;
        }
        //执行删除操作
        end.next=end.next.next;
        //因为head可能会被删除，所以返回pre.next
        return pre.next;
    }

}
